from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from libs.conn import execute, fetchone, fetchvalue, fetchall
from libs.utils import get_time

cmds_bp = Blueprint('cmds', __name__)


@cmds_bp.route('/api/add_cmd', methods=['POST'])
@jwt_required()
def add_cmd():
    client_id = request.json.get('client_id')
    cmd = request.json.get('cmd')
    if cmd is None or cmd.strip() == '':
        return { 'status': 'error', 'data': '指令不能为空' }
    cmd = cmd.strip()
    #cmd = base64.b64decode(cmd.encode('utf-8')).decode('utf-8')
    client_secret = fetchvalue("SELECT client_secret FROM clients WHERE client_id=?", (client_id,))
    if client_secret:
        cmd_id = execute("INSERT INTO cmds (client_id, cmd, result, complete, create_time) VALUES (?, ?, ?, ?, ?)", (client_id, cmd, '', 0, get_time()))
        return { 'status': 'ok', 'data': cmd_id }
    else:
        return { 'status': 'error', 'data': '下发指令失败，该客户端未注册密钥' }

@cmds_bp.route('/api/add_batch_cmd', methods=['POST'])
@jwt_required()
def add_batch_cmd():
    client_ids = request.json.get('client_ids')
    cmd = request.json.get('cmd')
    if cmd is None or cmd.strip() == '':
        return { 'status': 'error', 'data': '指令不能为空' }
    cmd = cmd.strip()
    for client_id in client_ids:
        client_secret = fetchvalue("SELECT client_secret FROM clients WHERE client_id=?", (client_id,))
        if client_secret:
            execute("INSERT INTO cmds (client_id, cmd, result, complete, create_time) VALUES (?, ?, ?, ?, ?)", (client_id, cmd, '', 0, get_time()))
    return { 'status': 'ok', 'data': 'success' }

@cmds_bp.route('/api/get_cmd_result', methods=['POST'])
@jwt_required()
def get_cmd_result():
    cmd_id = request.json.get('cmd_id')
    row = fetchone("SELECT complete, result FROM cmds WHERE cmd_id=?", (cmd_id,))
    if row:
        if row['complete'] == 1:
            return { 'status': 'ok', 'data': row['result'] }
        else:
            return { 'status': 'error', 'data': '指令未完成' }
    else:
        return { 'status': 'error', 'data': '指令不存在' }

@cmds_bp.route('/api/get_cmds', methods=['GET'])
@jwt_required()
def get_cmds():
    cmd_id = request.args.get('cmd_id')
    client_id = request.args.get('client_id')
    cmd = request.args.get('cmd')
    result = request.args.get('result')
    complete = request.args.get('complete')
    page_size = int(request.args.get('page_size'))
    page_current = int(request.args.get('page_current'))
    sql = "FROM cmds WHERE 1=1"
    params = []
    if cmd_id != None:
        sql += " AND cmd_id = ?"
        params.append(cmd_id)
    if client_id != None:
        sql += " AND client_id = ?"
        params.append(client_id)
    if cmd != None:
        sql += " AND cmd like ?"
        params.append('%'+cmd+'%')
    if result != None:
        sql += " AND result like ?"
        params.append('%'+result+'%')
    if complete != None:
        sql += " AND complete = ?"
        params.append(complete)
    offset = (page_current - 1) * page_size
    rows = fetchall('SELECT * ' + sql + ' ORDER BY cmd_id DESC LIMIT ? OFFSET ?', tuple(params + [page_size, offset]))
    total_count = fetchvalue('SELECT COUNT(*) ' + sql, tuple(params))
    return { 'status': 'ok', 'data': rows, 'page_total': total_count }

@cmds_bp.route('/api/delete_cmd', methods=['POST'])
@jwt_required()
def delete_cmd():
    cmd_id = request.json.get('cmd_id')
    execute("DELETE FROM cmds WHERE cmd_id = ?", (cmd_id,))
    return { 'status': 'ok', 'data': 'success' }


